/**
 *
 */
package com.beamfield.controller.manage.material;

import com.alibaba.fastjson.JSON;
import com.beamfield.common.ApiResult;
import com.beamfield.common.CommonUtils;
import com.beamfield.common.DateSwitcher;
import com.beamfield.common.PageResult;
import com.beamfield.controller.common.BaseController;
import com.beamfield.dictionary.code;
import com.beamfield.enums.HttpResultEnum;
import com.beamfield.model.Inbound;
import com.beamfield.model.InboundCheckWithBLOBs;
import com.beamfield.model.LabParameterRep;
import com.beamfield.modelVo.RebarInboundVo;
import com.beamfield.modelVo.SystemDictionaryDataVo;
import com.beamfield.service.manage.lab.LabParameterRepService;
import com.beamfield.service.manage.material.InboundService;
import com.beamfield.service.manage.material.PurchaseService;
import com.beamfield.service.manage.sys.DictonaryService;
import com.beamfield.service.manage.sys.ManufactorService;
import com.beamfield.service.manage.sys.SuppliesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 进场管理
 *
 * @author mintonzhang@163.com
 * @date 2018年6月13日
 */
@RestController
@RequestMapping("/cms")
public class InboundController extends BaseController {

	@Autowired
	private SuppliesService suppliesService;
	@Autowired
	private PurchaseService purchaseService;
	@Autowired
	private InboundService inboundService;
    @Resource
    private DictonaryService dictonaryService;
    @Resource
	private LabParameterRepService labParameterRepService;
    @Resource
	private ManufactorService manufactorService;

    @Value("${session.beam}")
	private String beam;

    @RequestMapping(value = "/material/material")
	public ModelAndView material(){
    	return new ModelAndView();
	}

    /**
     * 获取初始化处理进度
     * @param request
     * @return
     */
    @RequestMapping(value = "/material/inbound/getProgressData",method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getProgressData(HttpServletRequest request){
        Map<String,Double> resMap = new HashMap<>();
        Object progress = request.getSession().getAttribute("save_embed_progress");
        resMap.put("progressValue", progress == null ? 0L : (Double) progress);
        return new ApiResult(resMap);
    }

	/**
	 * 按照类型查询材料
	 *
	 * @date 2018年6月13日
	 * @author mintonzhang@163.com
	 * @param req
	 * @param type
	 * @return
	 */
	@RequestMapping("/material/inbound/getSuppliesByType")
	public ApiResult getSuppliesByType(HttpServletRequest req, String type) {
		try {
			if (CommonUtils.checkMissParam(type)) {
				return new ApiResult(HttpResultEnum.MIS_PARAM.getCode());
			}
			return suppliesService.getSuppliesByType(type, getBeamId(req));
		} catch (Exception e) {
			e.printStackTrace();
			return new ApiResult(HttpResultEnum.EXCEPTION.getCode());
		}
	}

	/**
	 * 根据材料id查询所有的计划及入库详细
	 *
	 * @date 2018年6月13日
	 * @author mintonzhang@163.com
	 * @param req
	 * @param supplies_id
	 * @return
	 */
	@RequestMapping("/material/inbound/getPurchaseBySuppliesId")
	public PageResult getPurchaseBySuppliesId(HttpServletRequest req, String supplies_id, String keyworks, String projectId,
			String status, Integer offset, Integer limit) {
		if (CommonUtils.checkMissParam(supplies_id)) {
			return new PageResult(0, 0, null);
		}
		return purchaseService.getPurchaseBySuppliesId(supplies_id, getBeamId(req), keyworks, status, projectId, offset, limit);
	}

	/**
	 * 查询计划详细
	 *
	 * @date 2018年6月14日
	 * @author mintonzhang@163.com
	 * @param req
	 * @param keywords
	 * @param date
	 * @param supplies_id
	 * @param plan_id
	 * @param offset
	 * @param limit
	 * @return
	 */
	@RequestMapping("/material/inbound/getPurchaseInboundDetail")
	public PageResult getPurchaseInboundDetail(HttpServletRequest req, String keywords, String date, String supplies_id,
			Long plan_id, Integer offset, Integer limit) {
		if (CommonUtils.checkMissParam(supplies_id, plan_id)) {
			return new PageResult(0, 0, null);
		}
		return inboundService.getPurchaseInboundDetail(supplies_id, getBeamId(req), keywords, date, plan_id, offset,
				limit);
	}

	/**
	 * 入库申请（普通）
	 * @date 2018年6月14日
	 * @author mintonzhang@163.com
	 * @param req
	 * @param itime_str
	 * @param inbound
	 * @return
	 */
	@RequestMapping("/material/inbound/saveInboundNomal")
	public ApiResult saveInboundNomal(HttpServletRequest req, String itime_str, Inbound inbound) {
		try {
			if (CommonUtils.checkMissParam(inbound,
					inbound.getBatch_number(),
					inbound.getProject_id(),
					inbound.getPurchase_plan_id(),
					inbound.getSupplies_id(),
					inbound.getManufacturer(),
					inbound.getLogisitcs_number(),
					//inbound.getProject_detail_id(),
					inbound.getNumber(),
					inbound.getStorage_place(),
					itime_str)) {
				return new ApiResult(HttpResultEnum.MIS_PARAM.getCode());
			}
			//处理接收的文件
			MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
			CommonsMultipartFile file = (CommonsMultipartFile) mRequest.getFile("file");
			if(file != null){
				Long id = saveFile(file);
				inbound.setQuality_file(id);
			}
			if(inbound.getInbound_id() != null){
				inbound.setUpdater(getUserId(req));
				inbound.setUpdatetime(new Date());

			}else{
				inbound.setAddtime(new Date());
				inbound.setBeam_id(getBeamId(req));
				inbound.setOperator(getUserId(req));
				inbound.setType(1);
				inbound.setUpdater(getUserId(req));
				inbound.setUpdatetime(new Date());
			}
			inbound.setItime(DateSwitcher.string2Date(itime_str,"yyyy-MM-dd"));
			manufactorService.save(inbound.getManufacturer(), getBeamId(req));
//			if(!inboundService.checkInbound(inbound)) {
//				return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),"入库数量超标");
//			}
			Long aLong = inboundService.saveInbound(inbound);
			if (aLong>0){
				return new ApiResult(HttpResultEnum.SUCCESS.getCode(),aLong+"");
			}else {
				return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),"服务器异常");
			}

		} catch (Exception e) {
			e.printStackTrace();
			return new ApiResult(HttpResultEnum.EXCEPTION.getCode());
		}
	}
	/**
	 * 入库申请（钢筋）
	 * @date 2018年6月14日
	 * @author mintonzhang@163.com
	 * @param req
	 * @param itime_str
	 * @param inbound
	 * @return
	 */
	@RequestMapping("/material/inbound/saveInboundRebar")
	public ApiResult saveInboundRebar(HttpServletRequest req, String itime_str, Inbound inbound, String rebarInbound) {
		try {
			if (CommonUtils.checkMissParam(inbound,
					inbound.getProject_id(),
					inbound.getPurchase_plan_id(),
					inbound.getSupplies_id(),
					inbound.getManufacturer(),
					inbound.getLogisitcs_number(),
					inbound.getStorage_place(),
					itime_str)) {
				return new ApiResult(HttpResultEnum.MIS_PARAM.getCode());
			}
			//处理接收的文件
			MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
			CommonsMultipartFile file = (CommonsMultipartFile) mRequest.getFile("file");
			if(file != null){
				Long id = saveFile(file);
				inbound.setQuality_file(id);
			}
			inbound.setAddtime(new Date());
			inbound.setBeam_id(getBeamId(req));
			inbound.setOperator(getUserId(req));
			inbound.setUpdater(getUserId(req));
			inbound.setUpdatetime(new Date());
			inbound.setType(2);
			inbound.setItime(DateSwitcher.string2Date(itime_str,"yyyy-MM-dd"));
			List<RebarInboundVo> rebarInboundVo = JSON.parseArray(rebarInbound, RebarInboundVo.class);
			//
//			if(!inboundService.checkRebarInbound(inbound,rebarInboundVo,getBeamId(req),getUserId(req))) {
//				return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),"入库数量超标");
//			}
			manufactorService.save(inbound.getManufacturer(), getBeamId(req));
			Long aLong = inboundService.saveInboundRebar(inbound, rebarInboundVo);
			return new ApiResult(HttpResultEnum.SUCCESS.getCode(),aLong+"");
		} catch (Exception e) {
			e.printStackTrace();
			return new ApiResult(HttpResultEnum.EXCEPTION.getCode());
		}
	}
	/**
	 * 入库申请(预埋件)
	 * @date 2018年6月14日
	 * @author mintonzhang@163.com
	 * @param req
	 * @param itime_str
	 * @param inbound
	 * @return
	 */
	@RequestMapping("/material/inbound/saveInboundEmbed")
	public ApiResult saveInboundEmbed(HttpServletRequest req, String itime_str,Integer count, Inbound inbound) {
		try {
			if (CommonUtils.checkMissParam(inbound,
					inbound.getProject_id(),
					inbound.getPurchase_plan_id(),
					inbound.getSupplies_id(),
					inbound.getManufacturer(),
					inbound.getLogisitcs_number(),
					inbound.getBatch_number(),
					inbound.getStorage_place(),
					itime_str,
					count)) {
				return new ApiResult(HttpResultEnum.MIS_PARAM.getCode());
			}
			//处理接收的文件
			MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
			CommonsMultipartFile file = (CommonsMultipartFile) mRequest.getFile("file");
			if(file != null){
				Long id = saveFile(file);
				inbound.setQuality_file(id);
			}
			inbound.setUpdater(getUserId(req));
			inbound.setUpdatetime(new Date());
			inbound.setAddtime(new Date());
			inbound.setBeam_id(getBeamId(req));
			inbound.setOperator(getUserId(req));
			inbound.setType(3);
			inbound.setNumber(count.doubleValue());
			inbound.setItime(DateSwitcher.string2Date(itime_str,"yyyy-MM-dd"));

//			if(!inboundService.checkInbound(inbound)) {
//				return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),"入库数量超标");
//			}
			//保存
			manufactorService.save(inbound.getManufacturer(), getBeamId(req));
			inboundService.saveEmbarInbound(inbound, count, req);
//			req.getSession().setAttribute("inbound_session" + getUserId(req), inbound);
//			req.getSession().setAttribute("inbound_session_int_data" + getUserId(req),count);
			return new ApiResult(HttpResultEnum.SUCCESS.getCode(),"操作成功", inbound.getInbound_id());

		} catch (Exception e) {
			e.printStackTrace();
			return new ApiResult(HttpResultEnum.EXCEPTION.getCode());
		}
	}

	@RequestMapping("/material/inbound/getCheckNum")
	public ApiResult getCheckNum(HttpServletRequest request){
        String checkDep = request.getParameter("checkDep");
        Long beamId = super.getBeamId(request);
        if(StringUtils.isEmpty(checkDep)){
            return new ApiResult();
        }
        String checkNum = inboundService.getCheckNum(checkDep, beamId);
        return new ApiResult(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage(), checkNum);
    }

	/**
	 * 入库申请检查单
	 * @date 2018年6月14日
	 * @author mintonzhang@163.com
	 * @param req
	 * @param wdate_str
	 * @param inboundCheck
	 * @return
	 */
	@RequestMapping("/material/inbound/saveInboundCheck")
	public ApiResult saveInboundCheck(HttpServletRequest req,String wdate_str,InboundCheckWithBLOBs inboundCheck,@RequestParam(required = false) String inboundid) {
		try {
			if (CommonUtils.checkMissParam(inboundCheck,
					inboundCheck.getCheck_dep(),
					inboundCheck.getSample_num(),
					inboundCheck.getTest_num(),
					inboundCheck.getRepresent_num(),
					inboundCheck.getStorage_place(),
					inboundCheck.getSite(),
					inboundCheck.getTest_standard(),
//					inboundCheck.getTest_project(),
					inboundCheck.getConsigner(),
//					inboundCheck.getAddress(),
					inboundCheck.getAuthorize_agency(),
					wdate_str)) {
				return new ApiResult(HttpResultEnum.MIS_PARAM);
			}
			inboundCheck.setBeam_id(getBeamId(req));
			inboundCheck.setUpdater(getUserId(req));
			inboundCheck.setUpdatetime(new Date());
			inboundCheck.setWdate(DateSwitcher.string2Date(wdate_str, "yyyy-MM-dd"));
			int i = inboundService.saveInboundAndCheck(inboundCheck, getUserId(req), getBeamId(req),req,inboundid);
			if(i == 2){
				return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),"委托编号已存在");
			}
			return new ApiResult(HttpResultEnum.SUCCESS.getCode(),"操作成功");
		} catch (Exception e) {
			e.printStackTrace();
			return new ApiResult(HttpResultEnum.EXCEPTION.getCode());
		}
	}

	@RequestMapping("/material/inbound/getDetailByInboundId")
	public PageResult getInboundDataById(Integer offset, Integer limit, Long inbound_id,Integer type) {
		if(CommonUtils.checkMissParam(inbound_id,type)) {
			return new PageResult(0, 0, null);
		}
		return inboundService.getInboundDataById(offset, limit, inbound_id, type);
	}

	/**
	 * 下载预埋件或者钢筋的入库二维码
	 * @param response
	 * @param inboundId
	 * @param inboundType
	 * @return
	 */
	@RequestMapping("/material/inbound/downloadInboundDetail")
	public String downloadInboundDetail(HttpServletResponse response, Long inboundId, Integer inboundType) {
		if(CommonUtils.checkMissParam(inboundId, inboundType)) {
			return "系统错误";
		}
		try {
			return inboundService.downloadInboundDetail(response, inboundId, inboundType);
		}catch (Exception e){
			e.printStackTrace();
			return "系统错误";
		}
	}
	/**普通材料入库
	 * @return
	 */
	@RequestMapping("/supplies/materialApproach/materialStorage")
	public ModelAndView materialStorage(){
		return new  ModelAndView();
	}
	@RequestMapping("/supplies/materialApproach/jieguotongzhiDetail")
	public ModelAndView jieguotongzhiDetail(){
		return new  ModelAndView();
	}


	/**
	 * 普通材料入库申请
	 * @return
	 */
	@RequestMapping("/supplies/materialApproach/materialStorageCheck")
	public ModelAndView materialStorageCheck(){
		return new  ModelAndView();
	}

	/**
	 * 预埋件
	 * @return
	 */
	@RequestMapping("/supplies/materialApproach/embed/embedStrage")
	public ModelAndView embedStrage(){
		return new  ModelAndView();
	}

	/**
	 * 预埋件
	 * @return
	 */
	@RequestMapping("/supplies/materialApproach/embed/embedStrageCheck")
	public ModelAndView embedStrageCheck(){
		return new  ModelAndView();
	}



	/**
	 * 主材料钢筋
	 * @return
	 */
	@RequestMapping("/supplies/materialApproach/rebar/rebarStrage")
	public ModelAndView rebarStrage(){
		return new  ModelAndView();
	}

	@RequestMapping("/material/inbound/getTestList")
	public List<LabParameterRep> getTestList(HttpServletRequest request){
		Long beamId = super.getBeamId(request);
		String suppliesId = request.getParameter("suppliesId");
		return labParameterRepService.getTestList(beamId,suppliesId);
	}

	/**
	 * 导出委托单
	 * @param request
	 */
	@RequestMapping("/material/inbound/exportOrder")
	@ResponseBody
	public ApiResult exportOrder(HttpServletRequest request, HttpServletResponse response){
		String id = request.getParameter("id");
		if(StringUtils.isBlank(id)){
			return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
		}
		return inboundService.exportOrder(id, response);
	}

	/**
	 * 获取入库信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/material/inbound/getInbound")
	@ResponseBody
	public ApiResult getInbound(HttpServletRequest request){
		String inboundId = request.getParameter("inbound_id");
		return inboundService.getInbound(inboundId);
	}

	@ResponseBody
	@RequestMapping("/material/inbound/deleteInbound")
	public ApiResult deleteInbound(HttpServletRequest request){
		String inboundId = request.getParameter("inboundId");
		return inboundService.deleteInbound(inboundId);
	}

	@ResponseBody
	@RequestMapping("/material/inbound/deleteOwnInboundCheck")
	public ApiResult deleteOwnInboundCheck(HttpServletRequest request){
		String id = request.getParameter("id");
		return inboundService.deleteOwnInboundCheck(id);
	}
}
